package com.yvon.service.demo.test.netty00;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

/**
 * 简单服务器
 *
 * @author Yvon
 * @date 2023-10-11
 */
@Slf4j
public class SimpleServer {
    public static void main(String[] args) throws IOException {
        // 创建服务端channel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 设置channel非阻塞
        serverSocketChannel.configureBlocking(false);
        // 得到服务端selector
        Selector selector = Selector.open();
        // 把channel注册到selector
        SelectionKey selectionKey = serverSocketChannel.register(selector, 0, serverSocketChannel);
        selectionKey.interestOps(SelectionKey.OP_ACCEPT);
        serverSocketChannel.bind(new InetSocketAddress(8080));
        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);
                    SelectionKey socketChannelKey  = socketChannel.register(selector, 0, socketChannel);
                    socketChannelKey .interestOps(SelectionKey.OP_READ);
                    log.info("客户端连接成功了");
                    socketChannel.write(ByteBuffer.wrap("我发送成功了".getBytes()));
                    log.info("向客户端发送数据成功");
                }
                if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel)key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int len = channel.read(byteBuffer);
                    if (len == -1) {
                        channel.close();
                        break;
                    } else {
                        byteBuffer.flip();
                        log.info("服务端读取到数据：" + new String(Charset.defaultCharset().decode(byteBuffer).toString()));
                    }
                }

            }
        }
    }
}
